﻿//************************************************************************************************
// Copyright © 2012 Steven M. Cohn. All Rights Reserved.
//
//************************************************************************************************ 

namespace CookieChipper
{
	using System;
	using System.IO;
	using System.Windows.Forms;


	internal partial class RestorePage : WizardPage
	{
		public RestorePage ()
		{
			InitializeComponent();

			base.Description = "Locate the backup file to restore";

			locationBox.Text = openFileDialog.InitialDirectory =
				Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
		}


		private void DoBrowse (object sender, EventArgs e)
		{
			DialogResult result = openFileDialog.ShowDialog(this);
			if (result == DialogResult.OK)
			{
				locationBox.Text = openFileDialog.FileName;
			}
		}


		private void DoTextChanged (object sender, EventArgs e)
		{
			string path = locationBox.Text.Trim();
			if (path.Length == 0)
			{
				pageState = PageStates.Empty;
			}
			else
			{
				string fullPath = Path.GetFullPath(path);
				PageState = (File.Exists(fullPath) ? PageStates.Ready : PageStates.Empty);
			}
		}


		private void DoVisibleChanged (object sender, EventArgs e)
		{
			DoTextChanged(sender, e);
			locationBox.Focus();
		}


		public override bool Execute ()
		{
			try
			{
				using (var backup = new BackupProvider(locationBox.Text))
				{
					backup.OpenWriter();
					int count = backup.Restore();

					base.Information =
						count.ToString() + " cookies restored from " + backup.FullPath;
				}
			}
			catch (Exception exc)
			{
				base.Information = exc.Message;
				return false;
			}
			return true;
		}
	}
}
